<template>
  <div class="sip-manage">
    <div class="tool">
      <div class="" style="float: left">
        <span @click.stop="addSipNum" class="main-color"><i class="el-icon-plus"></i><span>添加</span></span>
        <span @click.stop="exportData" class="main-color margin-l-10"><i class="iconfont icon-daochu1"></i><span>导出数据</span></span>
        <span @click.stop="handleBatch" class="main-color"><i class="iconfont icon-piliangchuli margin-l-10"></i><span>批量处理</span></span>
        <span @click.stop="reshList" class="main-color"><i class="iconfont icon-shuaxin margin-l-10"></i><span>刷新</span></span>
        <el-input
          style="width: 300px"
          class="margin-l-10"
          size="mini"
          placeholder="请输入SIP号进行查询"
          @keyup.native.enter="handlerClick"
          v-model.trim="query">
          <i
            class="el-input__icon el-icon-search"
            slot="suffix"
            @click="handlerClick">
          </i>
        </el-input>
        <el-popover
          placement="bottom"
          width="540"
          trigger="click"
        >
          <div style="font-size: 12px; padding: 5px;line-height:20px">
            <div>
            <div style="float: left">SIP号类型：</div>
            <el-checkbox-group v-model="checkList">
              <el-checkbox label="sip">软电话</el-checkbox>
              <el-checkbox label="gateway">网关</el-checkbox>
              <el-checkbox label="local">直线</el-checkbox>
            </el-checkbox-group>
            </div>
            <div style="text-align: center;margin-top: 20px">
              <el-button class='primary_btn' type="primary" @click='searchClick'>
                查询
              </el-button>
            </div>
          </div>
          <span slot="reference" class="main-color margin-l-10">高级搜索</span>
        </el-popover>
      </div>
      <div class="pag-wapper" style="float: right">
        <pagination
          style="float: left"
          :small="true"
          :currentPage="currentPage"
          :count="count"
          @turnPage="trunPages"
          :totalPage="Math.ceil(count/10)"
        >
        </pagination>
      </div>
    </div>
    <div class="table-wapper">
      <el-table
        :data="tableList"
        size="mini"
        highlight-current-row
        stripe
        style="width: 100%">
        <el-table-column label="SIP号" width="150"><template scope="scope">{{ scope.row.Exten }}</template></el-table-column>
        <el-table-column label="密码" width="150"><template scope="scope">{{ scope.row.Secret }}</template></el-table-column>
        <el-table-column label="SIP号类型" width="80"><template scope="scope">{{ scope.row.sipTypeName }}</template></el-table-column>
        <el-table-column label="所属工号"><template scope="scope">
          <agent
            :id="scope.row.UserID"
            isNum >
          </agent>
        </template></el-table-column>
        <el-table-column label="最后更新时间" width="150"><template scope="scope">{{ scope.row.UpdateTime }}</template></el-table-column>
        <el-table-column label="操作" width="100">
          <template scope="scope">
            <el-button type="text" size="small" @click="handleShow(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <left-slide :visible.sync='slideLeft' :title="slideName" @saveClick="handleSipCLick" @cancelClick="cancelClick" :showFooter="isShowBtn">
       <div class="add-sip" v-if="operateType === 'add'" style="margin: 20px">
         <div>请填写增加的数量：</div>
         <div style="margin-top: 7px">
           <el-input v-model="addSipForm.Amount"></el-input>
         </div>
         <div style="margin-top: 20px">
           <span>是否连续：</span>
           <el-radio-group v-model="addSipForm.IsSeries">
             <el-radio :label="true">是</el-radio>
             <el-radio :label="false">否</el-radio>
           </el-radio-group>
         </div>
       </div>
       <div v-if="operateType === 'show'" style="margin: 20px">
         <el-form ref="currentSip" :model="currentSip" labelPosition="top">
           <el-form-item label="SIP号">
             <el-input v-model="currentSip.Exten" disabled></el-input>
           </el-form-item>
           <el-form-item label="密码">
             <el-input v-model="currentSip.Secret" disabled></el-input>
           </el-form-item>
           <el-form-item label="绑定座席名称">
             <el-input v-model="currentSip.UserName" disabled></el-input>
           </el-form-item>
           <el-form-item label="绑定座席工号">
             <el-input style="width: 200px" v-model="currentSip.UserExten" :disabled="currentSip.ExtenType === 'gateway' ? false : true"></el-input>
             <el-button class = "primary_btn margin-l-10" type="primary" @click.stop='bindingClick' v-if="currentSip.ExtenType === 'gateway'">绑定</el-button>
           </el-form-item>
           <el-form-item label="支持编码" v-if="currentSip.ExtenType === 'gateway'">
             <el-select style="width: 400px;margin-top: 5px" v-model="codeData"  placeholder="请选择编码" multiple filterable allow-create default-first-option>
               <el-option
                 v-for="item in coding"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
               </el-option>
             </el-select>
           </el-form-item>
         </el-form>
       </div>
       <div v-if="operateType === 'batch'" style="margin: 20px">
         <sipBatchManage ref="sipBatchManage" @batchBindSuccess="batchBindSuccess"></sipBatchManage>
       </div>
    </left-slide>
  </div>
</template>
<script>
  import Agent from '@/components/public-modules/cache/Agent'
  import sipBatchManage from '@/components/business-modules/newConfig/callCenter/base/sipBatchManage.vue'
  import { ivrSearch, handleFakePage, deepClone } from '@/utils/m7Utils.js'
  import { checkform } from '@/utils/validate.js'
  import Pagination from '@/components/public-modules/card/Pagination'
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  export default {
    name: 'sipManage',
    data () {
      return {
        oldPBX: '',
        checkList: ['sip', 'gateway', 'local'],
        isShowBtn: false,
        codeData: [],
        coding: [
          {
            value: 'alaw',
            label: 'alaw'
          },
          {
            value: 'ulaw',
            label: 'ulaw'
          },
          {
            value: 'g729',
            label: 'g729'
          },
          {
            value: 'speex',
            label: 'speex'
          },
          {
            value: 'gsm',
            label: 'gsm'
          },
          {
            value: 'ilbc',
            label: 'ilbc'
          }
        ],
        operateType: '',
        slideName: '',
        rules: [],
        addSipForm: {
          IsSeries: false,
          Amount: 1
        },
        slideLeft: false,
        count: 0,
        currentPage: 1,
        query: '',
        currentSip: {},
        totalList: [],
        handledList: [],
        tableList: []
      }
    },
    components: {
      sipBatchManage,
      Agent,
      Pagination,
      leftSlide
    },
    watch: {
      pbx () {
        let routerName = this.$route.meta.title
        if (routerName === 'sipManage') {
          console.log('sipManage')
          this.reshList()
        }
      }
    },
    computed: {
      pbx () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    methods: {
      cancelClick () {
        this.slideLeft = false
      },
      batchBindSuccess () {
        this.slideLeft = false
        this.reshList()
      },
      searchClick () {
        let data = {
          Account: this.$store.state.session.account.account,
          PBX: this.pbx
        }
        this.checkList.indexOf('sip') > -1 ? data.sip = true : data.sip = false
        this.checkList.indexOf('gateway') > -1 ? data.gateway = true : data.gateway = false
        this.checkList.indexOf('local') > -1 ? data.local = true : data.local = false
        this.$store.dispatch('advantageSearchSip', data).then(resp => {
          if (resp && resp.success) {
            this.handleData(resp.list)
          }
        })
      },
      handleData (data) {
        let _list = []
        this.count = data.length
        if (data.length !== 0) {
          for (let i = 0; i < data.length; i++) {
            let _obj = data[i]
            _obj.sipTypeName = this.getSipTypeName(_obj.ExtenType)
            _list.push(_obj)
          }
        }
        this.query = ''
        this.currentPage = 1
        this.totalList = _list
        this.handledList = _list
        this.tableList = handleFakePage(this.currentPage, this.handledList)
      },
      bindingClick () {
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx]) {
          let newUserID = null
          let newUserName = null
          let agents = this.$store.state.session.ivrMap[this.pbx].data.account_user
          for (let i = 0; i < agents.length; i++) {
            if (agents[i].exten === this.currentSip.UserExten) {
              newUserID = agents[i]._id
              newUserName = agents[i].displayName
            }
          }
          if (newUserID == null) {
            this.$message.error('您绑定的工号不存在！')
            return
          }
          let data = {
            _id: this.currentSip.Exten,
            UserExten: this.currentSip.UserExten,
            PBX: this.pbx,
            UserID: newUserID,
            UserName: newUserName
          }
          this.$store.dispatch('bindGatewayUserExten', data).then(resp => {
            if (resp && resp.success) {
              this.currentSip.UserName = resp.data.UserName
              this.currentSip.UserExten = resp.data.UserExten
              console.log(this.currentSip)
              for (let i = 0; i < this.tableList.length; i++) {
                if (this.tableList[i]._id === resp.data._id) {
                  this.tableList[i].UserName = resp.data.UserName
                  this.tableList[i].UserExten = resp.data.UserExten
                  this.tableList[i].UserID = resp.data.UserID
                }
              }
              for (let i = 0; i < this.totalList.length; i++) {
                if (this.totalList[i]._id === resp.data._id) {
                  this.totalList[i].UserName = resp.data.UserName
                  this.totalList[i].UserExten = resp.data.UserExten
                  this.totalList[i].UserID = resp.data.UserID
                }
              }
              for (let i = 0; i < this.handledList.length; i++) {
                if (this.handledList[i]._id === resp.data._id) {
                  this.handledList[i].UserName = resp.data.UserName
                  this.handledList[i].UserExten = resp.data.UserExten
                  this.handledList[i].UserID = resp.data.UserID
                }
              }
              this.$message.success('绑定成功！')
            }
          })
        }
      },
      handleSipCLick () {
        if (this.operateType === 'add') {
          this.saveAddSip()
        } else if (this.operateType === 'show') {
          this.handleShowSip()
        } else if (this.operateType === 'batch') {
          this.$refs.sipBatchManage.saveBatch()
        }
      },
      handleShowSip () {
        let data = {
          _id: this.currentSip._id,
          Exten: this.currentSip.Exten,
          Secret: this.currentSip.Secret,
          UserName: this.currentSip.UserName || '',
          UserExten: this.currentSip.UserExten || '',
          Account: this.currentSip.Account,
          PBX: this.currentSip.PBX
        }
        if (this.currentSip.ExtenType === 'gateway' && this.codeData.length !== 0) {
          data.Allow = this.codeData.toString()
          data.codes = this.codeData
        }
        this.$store.dispatch('updateGatewayCodes', data).then(resp => {
          if (resp && resp.success) {
            this.slideLeft = false
            this.$message.success('保存成功!')
            this.reshList()
          }
        })
      },
      saveAddSip () {
        let myreg = checkform(this.addSipForm.Amount, 'Number')
        if (myreg) {
          this.$message.error(this.$t(myreg))
          return null
        } else if (this.addSipForm.Amount > 100 || this.addSipForm.Amount < 1) {
          this.$message.error('只能添加1~100个SIP号')
          return null
        }
        let data = {
          Account: this.$store.state.session.account.account,
          PBX: this.pbx,
          Amount: this.addSipForm.Amount,
          IsSeries: this.addSipForm.IsSeries
        }
        this.$store.dispatch('batchAddGatewaySip', data).then(resp => {
          if (resp && resp.success) {
            this.slideLeft = false
            this.$message.success('批量增加SIP号请求已成功提交,请手动刷新列表!')
          }
        })
      },
      trunPages (val) {
        this.currentPage = val
        this.tableList = handleFakePage(this.currentPage, this.handledList)
      },
      handleBatch () {
        this.operateType = 'batch'
        this.slideName = '批量管理'
        this.slideLeft = true
        this.isShowBtn = true
        this.$nextTick(function () {
          this.$refs.sipBatchManage.resetFormData()
        })
      },
      exportData () {
        let data = {
          Method: 'exportSipInfoExcel',
          Query: {
            accountId: this.$store.state.session.account.account,
            condition: this.query,
            pbx: this.pbx
          }
        }
        this.checkList.indexOf('sip') > -1 ? data.Query.sip = 'true' : data.Query.sip = 'false'
        this.checkList.indexOf('gateway') > -1 ? data.Query.gateway = 'true' : data.Query.gateway = 'false'
        this.checkList.indexOf('local') > -1 ? data.Query.Local = 'true' : data.Query.Local = 'false'
        this.$store.dispatch('exportSipList', data).then(resp => {})
      },
      handleShow (obj) {
        this.operateType = 'show'
        this.slideName = 'SIP号详细信息'
        this.slideLeft = true
        this.currentSip = deepClone(obj)
        if (this.currentSip.ExtenType === 'gateway') {
          this.isShowBtn = true
          if (obj.Allow && obj.Allow !== '') {
            this.codeData = obj.Allow.split(',')
          } else {
            this.codeData = []
          }
        } else {
          this.isShowBtn = false
        }
      },
      addSipNum () {
        this.operateType = 'add'
        this.slideName = '添加SIP号'
        this.slideLeft = true
        this.isShowBtn = true
        this.addSipForm.IsSeries = false
        this.addSipForm.Amount = 1
      },
      handlerClick () {
        this.handledList = ivrSearch(this.totalList, this.query, ['Exten']) || []
        this.count = this.handledList.length || 0
        this.currentPage = 1
        this.tableList = handleFakePage(this.currentPage, this.handledList)
      },
      fetchData () {
        this.$store.dispatch('querySipRefresh', {Account: this.$store.state.session.account.account, PBX: this.pbx}).then(resp => {
          if (resp && resp.success) {
            this.handleData(resp.list)
          }
        })
      },
      getSipTypeName (sipType) {
        let sipDic = this.$getCache('sipType')
        let str = ''
        if (sipDic && sipDic.length !== 0) {
          for (let i = 0; i < sipDic.length; i++) {
            if (sipDic[i].code_value === sipType) {
              str = sipDic[i].code_name
              break
            }
          }
        }
        return str
      },
      reshList () {
        this.fetchData()
      }
    },
    deactivated () {
      this.oldPBX = this.pbx
    },
    activated () {
      if (this.oldPBX !== this.pbx) {
        this.reshList()
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'sipType'}).then(() => {
        this.fetchData()
      })
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .sip-manage
    margin 20px
    overflow-y hidden
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    overflow-y: auto;
    font-size: 12px;
    .margin-t-10
      margin-top 10px
    .margin-l-10
      margin-left 10px
    .pag-wapper
      position: absolute;
      right: 15px;
      top: 14px;
    .main-color
      color $c-main
      cursor pointer
    .wapper
      display flex
      flex-direction column
    .tool
      position relative
      border 1px solid #e7e7eb
      border-bottom 0
      padding  12px 15px
      /*display flex*/
      justify-content space-between
    .primary_btn
      padding 0px 10px
      min-width 60px
</style>

